<?php 
// +----------------------------------------------------------------------
// | YBlog
// +----------------------------------------------------------------------
// | Copyright (c) 2008 http://www.yhustc.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: yhustc <yhustc@gmail.com>
// +----------------------------------------------------------------------
// $Id$

/**
 +------------------------------------------------------------------------------
 * YBlog插件管理模块
 +------------------------------------------------------------------------------
 * @author    yhustc <yhustc@gmail.com>
 * @version   $Id$
 +------------------------------------------------------------------------------
 */
import('@.Action.BaseAction');

class PlugInAction extends BaseAction
{
	/**
     +----------------------------------------------------------
     * 插件列表
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */
    function index()
    {
        $this->flesh();
		
		$pluginDao = D("PlugIn");
		$total = $pluginDao->count();
		import("ORG.Util.Page");
		$page = new Page($total,20);
		$plugInList = $pluginDao->where("type='plugin'")->limit($page->firstRow.",".$page->listRows)->findAll();

        $this->assign("pageFile","PlugIn:index");
		$this->assign("plugInList",$plugInList);
		$this->assign("navigation",$page->show());
		$this->layout();
    }
    
    /**
     +----------------------------------------------------------
     * 编辑插件文件
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */
    function edit()
    {
    	$pluginDao = D("PlugIn");
    	$plugin = $pluginDao->getById($_GET["id"]);
    	
    	$this->assign("pageFile","PlugIn:edit");
		$this->assign("plugin",$plugin);
		$this->layout();
    }
    
    /**
     +----------------------------------------------------------
     * 保存对插件文件的编辑
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */
    function save()
    {
    	$count = file_put_contents($_POST["file"],$_POST["content"]);
    	if($count > 0)
    	{
    		//写入成功,更新缓存
    		$this->_writePlugin();
    		$this->success("更新插件文件成功!");
    	}
    	else
    		$this->error("更新插件文件失败!");
    }
    
	/**
     +----------------------------------------------------------
     * 检查插件更新
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */            
    function flesh()
    {
		// 加载插件必须的函数
        include THINK_PATH.'/Common/plugin.php';
		$plugins = get_plugins(BLOG_PATH.'/PlugIns','Plugin');// 项目插件
		foreach($plugins as $key=>$value)
			$plugins[$key]["type"] = "plugin";

		$widgets = get_plugins(BLOG_PATH.'/Lib/Widget','Widget');// 项目插件
		foreach($widgets as $key=>$value)
			$widgets[$key]["type"] = "widget";

        $this->_add_app_plugin(array_merge($plugins,$widgets));

        return ;
    }
	
	/**
     +----------------------------------------------------------
     * 添加新插件到插件表中
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */
    function _add_app_plugin($plugins) 
    {
		$pluginDao = D("PlugIn");
		$plugs = "";
		foreach($plugins as $plugin)			
			$plugs .= "'".$plugin['name']."',";
		
		//先把无效的插件删除
		$pluginDao->delete("name NOT IN (".rtrim($plugs,",").")");

        foreach($plugins as $key=>$plugin) {
            $result = $pluginDao->find('name="'.$plugin['name'].'"');
            if(!$result) {
                // 如果数据库不存在该插件 添加
                $plugin['status'] =  0; //默认为禁用
                $pluginDao->add($plugin);
            }
			else if($result["file"] != $plugin["file"])
			{
				//有可能是移动了目录 插件是有记录的 但是插件文件的路径变化了
				//需要更新路径 否则写插件缓存时取不到所需的文件
				//启用状态不需要变,直接把file改了就行了
				$pluginDao->setField("file",$plugin["file"],"name='".$plugin['name']."'");
			}
        }
        return ;
    }
	
	/**
     +----------------------------------------------------------
     * 修改插件的启用/禁用状态
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */
	function changeStatus()
	{
		$pluginDao = D("PlugIn");
		$rs = $pluginDao->setField("`status`",$_GET["status"],"id='".$_GET["id"]."'");

		if(!$rs)
			$this->error("修改插件配置失败");

		$this->_writePlugin();
		$this->success("修改插件配置成功");
	}
	
	/**
     +----------------------------------------------------------
     * 写入插件缓存
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */
    function _writePlugin()
    {
        $pluginDao = D("PlugIn");
        $plugins = $pluginDao->where("status=1 and type='plugin'")->field("file")->findAll();

        // 缓存启用的插件数据
		$content = '';
		foreach($plugins as $key=>$val) {
			$content .= php_strip_whitespace($val['file']);
		}
        $count = file_put_contents(BLOG_PATH."/Temp/~plugins.php",$content);
		if($count > 0) //$count为写入字节数     	
        	return ;
        else
        	$this->error("写入插件缓存文件出错!");
    }
	
	/**
     +----------------------------------------------------------
     * widget顺序的调整
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */
	function widget()
	{
		$this->flesh();
		
		$pluginDao = D("PlugIn");
		$widgets = $pluginDao->where("type='widget'")->field("id,name,description,status")->order("priority ASC")->findAll();
		$offWidget = $onWidget = array();
		foreach($widgets as $widget)
		{
			if($widget["status"] == "1")
				$onWidget[] = $widget;
			else
				$offWidget[] = $widget;
		}

		$this->assign("pageFile","PlugIn:widget");
		$this->assign("offWidget",$offWidget);
		$this->assign("onWidget",$onWidget);
		$this->layout();
	}
	
	/**
     +----------------------------------------------------------
     * 保存widget的顺序
     +----------------------------------------------------------
     * @access public 
     +----------------------------------------------------------
     */
	function widgetConfig()
	{
		$offWidget = str_replace("&",",",str_replace("offWidget[]=","",$_POST["offWidget"]));
		$onWidget = str_replace("&",",",str_replace("onWidget[]=","",$_POST["onWidget"]));
		
		$rs1 = $rs2 = true;
		$pluginDao = D("PlugIn");
		if(!empty($offWidget))
			$rs1 = $pluginDao->setField("`status`","0","id IN (".rtrim($offWidget,',').")");
		if(!empty($onWidget))
			$rs2 = $pluginDao->setField("`status`","1","id IN (".rtrim($onWidget,',').")");
	
		/*由于在没有记录没作任何改变的时候,setField有可能返回int(0),下面这两行无法准确的判断SQL的执行情况*/
		//if(!$rs1 || !$rs2)
		//	$this->error("保存widget配置失败");

		//保存widget输出的顺序
		$widgetArray = explode(",",$onWidget);
		foreach($widgetArray as $key=>$id)
			$pluginDao->setField("`priority`",($key+1),"id='".$id."'");
		
		/*由于S函数无法操作BlogApp的缓存,S("widgets")无法更新,干脆不写~plugin.php了,改为清空,由BlogApp自己重新生成缓存*/
		//$this->_writePlugin();
		clearBlogCache();
		$this->success("保存widget配置成功");
	}
}
?>